from fastapi import APIRouter, HTTPException, Depends, Query, Body
from typing import List, Optional, Dict, Any
import logging

from backend.schemas.agent import (
    AgentCreate, AgentOut, AgentUpdate, AgentList, PaginationParams,
    AgentSearchRequest, AgentCopyRequest
)
from backend.services.agent_service import AgentService
from backend.common.jwt import get_current_active_user, require_permissions
from backend.schemas.response import ResponseBase
from backend.models.user import User

# 配置日志
logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("/agent", response_model=ResponseBase[AgentOut], summary="创建智能体")
async def create_agent(
    agent_data: AgentCreate,
    current_user: User = Depends(get_current_active_user)
):
    """创建新的智能体"""
    try:
        logger.info(f"用户 {current_user.id} 正在创建智能体: {agent_data.name}")
        
        agent = await AgentService.create_agent(agent_data, current_user)
        
        # 使用服务层的统一转换方法
        agent_dict = AgentService._agent_to_dict(agent)
        agent_out = AgentOut(**agent_dict)
        
        logger.info(f"智能体创建成功: ID={agent.id}, 名称={agent.name}")
        return ResponseBase[AgentOut](data=agent_out, message="智能体创建成功")
        
    except ValueError as e:
        logger.warning(f"创建智能体参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except PermissionError as e:
        logger.warning(f"创建智能体权限不足: {str(e)}")
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        logger.error(f"创建智能体失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"创建智能体失败: {str(e)}")


@router.get("/agent", response_model=ResponseBase[AgentList], summary="获取智能体列表")
async def get_agents(
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(10, ge=1, le=100, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    agent_type: Optional[str] = Query(None, description="智能体类型（新字段）"),
    type: Optional[str] = Query(None, description="智能体类型（兼容旧字段）"),
    category: Optional[str] = Query(None, description="智能体分类"),
    status: Optional[str] = Query(None, description="智能体状态"),
    department_id: Optional[str] = Query(None, description="部门ID"),
    is_public: Optional[bool] = Query(None, description="是否公开"),
    include_deleted: bool = Query(False, description="是否包含已删除的记录"),
    current_user: User = Depends(get_current_active_user)
):
    """获取智能体列表，支持分页和筛选"""
    try:
        logger.info(f"用户 {current_user.id} 正在获取智能体列表")
        
        params = PaginationParams(
            page=page,
            limit=limit,
            search=search,
            agent_type=agent_type or type,  # 优先使用新字段，兼容旧字段
            category=category,
            status=status,
            department_id=department_id,
            is_public=is_public,
            include_deleted=include_deleted
        )
        
        agents, total = await AgentService.get_agents_list(params, current_user)
        
        agent_list = AgentList(
            items=[AgentOut(**agent) for agent in agents],
            total=total,
            page=page,
            limit=limit
        )
        
        logger.info(f"成功获取智能体列表: 总数={total}, 当前页={page}")
        return ResponseBase[AgentList](data=agent_list)
        
    except Exception as e:
        logger.error(f"获取智能体列表失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取智能体列表失败: {str(e)}")


@router.get("/agent/{agent_id}", response_model=ResponseBase[AgentOut], summary="获取智能体详情")
async def get_agent(
    agent_id: int,
    current_user: User = Depends(get_current_active_user)
):
    """获取指定智能体的详细信息"""
    try:
        logger.info(f"用户 {current_user.id} 正在获取智能体详情: ID={agent_id}")
        
        # 使用服务层的权限检查方法
        agent = await AgentService.get_agent_by_id(agent_id, current_user)
        if not agent:
            raise HTTPException(status_code=404, detail="智能体不存在或您没有权限访问")
        
        # 使用服务层的统一转换方法
        agent_dict = AgentService._agent_to_dict(agent)
        agent_out = AgentOut(**agent_dict)
        
        logger.info(f"成功获取智能体详情: ID={agent_id}, 名称={agent.name}")
        return ResponseBase[AgentOut](data=agent_out)
        
    except HTTPException:
        raise
    except PermissionError as e:
        logger.warning(f"获取智能体详情权限不足: {str(e)}")
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        logger.error(f"获取智能体详情失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取智能体详情失败: {str(e)}")


@router.put("/agent/{agent_id}", response_model=ResponseBase[AgentOut], summary="更新智能体")
async def update_agent(
    agent_id: int,
    agent_data: AgentUpdate,
    current_user: User = Depends(get_current_active_user)
):
    """更新指定智能体的信息"""
    try:
        logger.info(f"用户 {current_user.id} 正在更新智能体: ID={agent_id}")
        
        agent = await AgentService.update_agent(agent_id, agent_data, current_user)
        if not agent:
            raise HTTPException(status_code=404, detail="智能体不存在")
        
        # 使用服务层的统一转换方法
        agent_dict = AgentService._agent_to_dict(agent)
        agent_out = AgentOut(**agent_dict)
        
        logger.info(f"智能体更新成功: ID={agent_id}, 名称={agent.name}")
        return ResponseBase[AgentOut](data=agent_out, message="智能体更新成功")
        
    except PermissionError as e:
        logger.warning(f"更新智能体权限不足: {str(e)}")
        raise HTTPException(status_code=403, detail=str(e))
    except ValueError as e:
        logger.warning(f"更新智能体参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"更新智能体失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"更新智能体失败: {str(e)}")


@router.delete("/agent/{agent_id}", response_model=ResponseBase[None], summary="删除智能体（软删除）")
async def delete_agent(
    agent_id: int,
    current_user: User = Depends(get_current_active_user)
):
    """删除指定的智能体（软删除，将状态设为deleted）"""
    try:
        logger.info(f"用户 {current_user.id} 正在删除智能体: ID={agent_id}")
        
        success = await AgentService.delete_agent(agent_id, current_user)
        if not success:
            raise HTTPException(status_code=404, detail="智能体不存在")
        
        logger.info(f"智能体删除成功: ID={agent_id}")
        return ResponseBase[None](message="智能体删除成功")
        
    except PermissionError as e:
        logger.warning(f"删除智能体权限不足: {str(e)}")
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        logger.error(f"删除智能体失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"删除智能体失败: {str(e)}")


@router.delete("/agent/{agent_id}/hard", response_model=ResponseBase[None], summary="永久删除智能体")
async def hard_delete_agent(
    agent_id: int,
    current_user: User = Depends(get_current_active_user)
):
    """永久删除指定的智能体（硬删除，从数据库中彻底删除）"""
    try:
        logger.info(f"用户 {current_user.id} 正在永久删除智能体: ID={agent_id}")
        
        success = await AgentService.hard_delete_agent(agent_id, current_user)
        if not success:
            raise HTTPException(status_code=404, detail="智能体不存在")
        
        logger.info(f"智能体永久删除成功: ID={agent_id}")
        return ResponseBase[None](message="智能体永久删除成功")
        
    except PermissionError as e:
        logger.warning(f"永久删除智能体权限不足: {str(e)}")
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        logger.error(f"永久删除智能体失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"永久删除智能体失败: {str(e)}")


@router.get("/agent/search", response_model=ResponseBase[List[AgentOut]], summary="搜索智能体")
async def search_agents(
    keyword: str = Query(..., description="搜索关键词"),
    limit: int = Query(10, ge=1, le=50, description="返回数量限制"),
    current_user: User = Depends(get_current_active_user)
):
    """根据关键词搜索智能体"""
    try:
        logger.info(f"用户 {current_user.id} 正在搜索智能体: 关键词={keyword}")
        
        agents = await AgentService.search_agents(keyword, current_user, limit)
        agent_outs = [AgentOut(**AgentService._agent_to_dict(agent)) for agent in agents]
        
        logger.info(f"搜索完成: 找到 {len(agents)} 个智能体")
        return ResponseBase[List[AgentOut]](data=agent_outs)
        
    except Exception as e:
        logger.error(f"搜索智能体失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"搜索智能体失败: {str(e)}")


@router.get("/agent/count", response_model=ResponseBase[int], summary="获取用户智能体数量")
async def get_user_agents_count(
    user_id: Optional[int] = Query(None, description="用户ID，不传则获取当前用户"),
    current_user: User = Depends(get_current_active_user)
):
    """获取指定用户的智能体数量"""
    try:
        target_user_id = user_id if user_id else current_user.id
        logger.info(f"用户 {current_user.id} 正在获取用户 {target_user_id} 的智能体数量")
        
        count = await AgentService.get_user_agents_count(target_user_id, current_user)
        
        logger.info(f"用户 {target_user_id} 的智能体数量: {count}")
        return ResponseBase[int](data=count)
        
    except PermissionError as e:
        logger.warning(f"获取智能体数量权限不足: {str(e)}")
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        logger.error(f"获取智能体数量失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取智能体数量失败: {str(e)}")


@router.post("/agent/{agent_id}/copy", response_model=ResponseBase[AgentOut], summary="复制智能体")
async def copy_agent(
    agent_id: int,
    copy_data: Optional[AgentCopyRequest] = None,
    current_user: User = Depends(get_current_active_user)
):
    """复制指定的智能体"""
    try:
        logger.info(f"用户 {current_user.id} 正在复制智能体: ID={agent_id}")
        
        new_agent = await AgentService.copy_agent(agent_id, current_user, copy_data)
        if not new_agent:
            raise HTTPException(status_code=404, detail="源智能体不存在或您没有权限访问")
        
        # 使用服务层的统一转换方法
        agent_dict = AgentService._agent_to_dict(new_agent)
        agent_out = AgentOut(**agent_dict)
        
        logger.info(f"智能体复制成功: 源ID={agent_id}, 新ID={new_agent.id}")
        return ResponseBase[AgentOut](data=agent_out, message="智能体复制成功")
        
    except PermissionError as e:
        logger.warning(f"复制智能体权限不足: {str(e)}")
        raise HTTPException(status_code=403, detail=str(e))
    except ValueError as e:
        logger.warning(f"复制智能体参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"复制智能体失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"复制智能体失败: {str(e)}")




@router.get("/agent/types", response_model=ResponseBase[List[str]], summary="获取智能体类型列表")
async def get_agent_types(
    current_user: User = Depends(get_current_active_user)
):
    """获取可用的智能体类型列表"""
    try:
        types = await AgentService.get_agent_types()
        return ResponseBase[List[str]](data=types)
    except Exception as e:
        logger.error(f"获取智能体类型失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取智能体类型失败: {str(e)}")


@router.get("/agent/categories", response_model=ResponseBase[List[str]], summary="获取智能体分类列表")
async def get_agent_categories(
    current_user: User = Depends(get_current_active_user)
):
    """获取可用的智能体分类列表"""
    try:
        categories = await AgentService.get_agent_categories()
        return ResponseBase[List[str]](data=categories)
    except Exception as e:
        logger.error(f"获取智能体分类失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取智能体分类失败: {str(e)}")


@router.get("/agent/statuses", response_model=ResponseBase[List[str]], summary="获取智能体状态列表")
async def get_agent_statuses(
    current_user: User = Depends(get_current_active_user)
):
    """获取可用的智能体状态列表"""
    try:
        statuses = await AgentService.get_agent_statuses()
        return ResponseBase[List[str]](data=statuses)
    except Exception as e:
        logger.error(f"获取智能体状态失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取智能体状态失败: {str(e)}")


@router.get("/agent/{agent_id}/export", response_model=ResponseBase[Dict[str, Any]], summary="导出智能体配置")
async def export_agent(
    agent_id: int,
    current_user: User = Depends(get_current_active_user)
):
    """导出指定智能体的配置信息"""
    try:
        logger.info(f"用户 {current_user.id} 正在导出智能体配置: ID={agent_id}")
        
        config = await AgentService.export_agent_config(agent_id, current_user)
        if not config:
            raise HTTPException(status_code=404, detail="智能体不存在或您没有权限访问")
        
        logger.info(f"智能体配置导出成功: ID={agent_id}")
        return ResponseBase[Dict[str, Any]](data=config, message="智能体配置导出成功")
        
    except PermissionError as e:
        logger.warning(f"导出智能体配置权限不足: {str(e)}")
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        logger.error(f"导出智能体配置失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"导出智能体配置失败: {str(e)}")


@router.post("/agent/import", response_model=ResponseBase[AgentOut], summary="导入智能体配置")
async def import_agent(
    config: Dict[str, Any] = Body(...),
    current_user: User = Depends(get_current_active_user)
):
    """导入智能体配置并创建新的智能体"""
    try:
        logger.info(f"用户 {current_user.id} 正在导入智能体配置")
        
        agent = await AgentService.import_agent_config(config, current_user)
        
        # 使用服务层的统一转换方法
        agent_dict = await AgentService._agent_to_dict(agent)
        agent_out = AgentOut(**agent_dict)
        
        logger.info(f"智能体配置导入成功: ID={agent.id}, 名称={agent.name}")
        return ResponseBase[AgentOut](data=agent_out, message="智能体配置导入成功")
        
    except ValueError as e:
        logger.warning(f"导入智能体配置参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"导入智能体配置失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"导入智能体配置失败: {str(e)}")
